package com.xiaoxu.entry.bishi;

import java.util.Arrays;
import java.util.HashMap;

/**
 * 求两数之和
 */
public class TowSum {
    public static void main(String[] args) {
        int[] nums = {2,8,11,15,7};
        int target = 9;
        int[] ints = twoSum(nums, target);
        System.out.println(Arrays.toString(ints));
        int[] map = twoSumByMap(nums, target);
        System.out.println(Arrays.toString(map));

    }

    /**
     *暴力法
     */
    public static  int[] twoSum(int[] nums, int target) {
        int[] result = new int[2];
        for (int i = 0;i<nums.length;i++){
            for (int j = i+1;j<nums.length;j++){
                if (nums[i] + nums[j] == target){
                    result[0] = i;
                    result[1] = j;
                    break;
                }
            }
        }
        return result;
    }

    /**
     *hash表法
     */
    public static  int[] twoSumByMap(int[] nums, int target) {
        int[] result = new int[2];
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0;i<nums.length;i++){
            map.put(nums[i],i);
        }
        for (int i = 0;i<nums.length;i++){
            int temp = target-nums[i];
            if (map.containsKey(temp)){
                Integer index = map.get(temp);
                result[0] = i;
                result[1] = index;
                break;
            }
        }
        return result;
    }

}

